#include "battery.h"
#include "adc.h"
#include "ledStatus.h"
#include "stateControl.h"

#include "debug.h"

// 10k,10k电阻，如果电阻更换，重新更改该参数
#define VOL_COFF 2
#define BAT_LOW_VOL 3.0f //3.25
#define TIMEOUT_VAL (10u)
#define ADC1_ACCURACY (1ul<<(12u)) 
#define ADC_VREF (3.288f)
static float batVol;							
//static uint16_t m_au16AdcValue[ADC1_CH_COUNT];	
												
void updateBat(void)							
{	
    uint16_t batAdc = 0;
    getChannelValue(9, &batAdc);
	
//	for(int i=0;i<ADC1_CH_COUNT;i++)	
//	{
//		m_au16AdcValue[i]=ADC_GetValue(M4_ADC1,i);
//	}
//	只有10位adc
    batVol = VOL_COFF * (batAdc* ADC_VREF) / (float)ADC1_ACCURACY ; 
//	[0]=m_au16AdcValue[9];
//  [1]=batVol*1000; 
    // 电压低通 
    static float batVolLpf;
    batVolLpf += (batVol - batVolLpf) * 0.3f;
//  [2]=batVolLpf*1000;
	
    // 低电判断
    static uint8_t lowCount;
    if (batVolLpf < BAT_LOW_VOL)
    {
        // 5秒, 50hz需要250次
        lowCount++;
        if (lowCount > 250)
        {
            lowCount = 251;
            setStatus(LOW_BAT);
            // 飞机自动降落
            setFlightState(CONTROL_MODE_LAND);
        }
    }
    else
    {
        lowCount = 0;
    }
}

float getBatVol(void)
{
    return batVol;
}

float getM1Vol(void)
{
	float m1Vol;	
    uint16_t adc = 0;
    getChannelValue(2, &adc);
	m1Vol = VOL_COFF * (adc* ADC_VREF) / (float)ADC1_ACCURACY ; 
    return m1Vol;
}

float getM2Vol(void)
{
	float m2Vol;	
    uint16_t adc = 0;
    getChannelValue(3, &adc);
	m2Vol = VOL_COFF * (adc* ADC_VREF) / (float)ADC1_ACCURACY ; 
    return m2Vol;
}
float getM3Vol(void)
{
	float m3Vol;	
    uint16_t adc = 0;
    getChannelValue(4, &adc);
	m3Vol = VOL_COFF * (adc* ADC_VREF) / (float)ADC1_ACCURACY ; 
    return m3Vol;
}
float getM4Vol(void)
{
	float m4Vol;	
    uint16_t adc = 0;
    getChannelValue(5, &adc);
	m4Vol = VOL_COFF * (adc* ADC_VREF) / (float)ADC1_ACCURACY ; 
    return m4Vol;
}
